package org.jiuling.basics.converter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;

/**
 * 数据流转换
 * @author 紫灵
 * @date 2024年01月31日 14时33分46秒
 */
public class InputStreamConvert {

    /**
     * 数据流转String
     * @param inputStream 数据流
     * @return 字符串
     */
    public static String toString(InputStream inputStream) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            if (Objects.nonNull(inputStream)) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                int bytesRead;
                char[] charBuffer = new char[128];
                while ((bytesRead = bufferedReader.read(charBuffer)) != -1) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        return stringBuilder.toString();
    }

}
